/*
 * Copyright (C) 2012 SeekDeepWithin.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.seekdeepwithin.Controls;

import com.seekdeepwithin.Data.Html;
import com.seekdeepwithin.Resources.*;
import java.util.*;
import javafx.beans.value.*;
import javafx.concurrent.*;
import javafx.scene.layout.*;
import javafx.scene.web.*;
import netscape.javascript.JSObject;

/**
 * User: Jonathan Montiverdi
 * Date: Oct 11, 2012
 *
 * A wrapper for the web view.
 */
public class WebControl extends HBox
{
   private WebView m_WebView;
   private boolean m_Loaded;
   private final ArrayList<String> m_Scripts;

   /**
    * Initializes a new web control.
    */
   public WebControl ()
   {
      this.m_Loaded = false;
      this.m_Scripts = new ArrayList<> ();
      this.m_WebView = new WebView ();
      this.m_WebView.setContextMenuEnabled (false);
      HBox.setHgrow (this.m_WebView, Priority.ALWAYS);
      this.getChildren ().add (this.m_WebView);
   }

   /**
    * Sets the web event handler.
    * @param handler Web event handler.
    */
   public void setHandler (final IWebEventHandler handler)
   {
      if (handler == null) {
         return;
      }

      final WebEngine engine = this.m_WebView.getEngine ();
      engine.getLoadWorker ().stateProperty ().addListener (new ChangeListener<Worker.State> ()
      {
         @Override
         public void changed (ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState)
         {
            if (newState == Worker.State.SUCCEEDED) {
               JSObject app = (JSObject) engine.executeScript ("window");
               app.setMember ("app", new JavaActions (handler, engine));
               engine.executeScript ("$(\"a\").click(function(event){event.preventDefault();});");
               m_Loaded = true;
               for (String script : m_Scripts) {
                  engine.executeScript (script);
               }
               m_Scripts.clear ();
            }
         }
      });

      /*engine.getLoadWorker ().exceptionProperty ().addListener (new ChangeListener<Throwable> () {
       @Override public void changed (ObservableValue<? extends Throwable> ov, Throwable oldThrowable, Throwable newThrowable)
       {
       // Display exceptions?
       }
       });*/
   }

   /**
    * Sets the HTML to display.
    * @param html HTML to display.
    */
   public void setHtml (String html)
   {
      this.setHtml (html, "");
   }

   /**
    * Sets the HTML to display.
    * @param html HTML to display.
    * @param additionalScripts Any additional scripts to add to the page.
    */
   public void setHtml (String html, String additionalScripts)
   {
      this.setHtml (html, additionalScripts, true);
   }

   /**
    * Sets the HTML to display.
    * @param html HTML to display.
    * @param additionalScripts Any additional scripts to add to the page.
    * @param fragment True if given HTML is a fragment, false if the HTML is fully created.
    */
   public void setHtml (String html, String additionalScripts, boolean fragment)
   {
      this.m_Loaded = false;
      WebEngine engine = this.m_WebView.getEngine ();
      StringBuilder builder = new StringBuilder ();
      if (fragment) {
         StringBuilder scripts = new StringBuilder ();
         scripts.append (SdwResources.getJsLink (SdwResources.JQUERY_2_0_3))
                 .append (Html.Newline)
                 .append (SdwResources.getJsLink (SdwResources.QTIP_JS))
                 .append (Html.Newline);
         StringBuilder styles = new StringBuilder ();
         styles.append (SdwResources.getCssLink (SdwResources.QTIP_CSS))
                 .append (Html.Newline)
                 .append (SdwResources.getCssLink (SdwResources.BOOTSTRAP));
         builder.append (Html.getPageStart (styles.toString ()))
                 .append (additionalScripts)
                 .append (Html.getCss ())
                 .append (Html.getBodyStart ())
                 .append (html)
                 .append (scripts.toString ())
                 .append (Html.getPageEnd ());
      } else {
         builder.append (html);
      }
      engine.loadContent (builder.toString ());
   }

   /**
    * Executes the given java script.
    * @param script Java script to execute.
    */
   public void executeJS (String script)
   {
      if (this.m_Loaded) {
         WebEngine engine = this.m_WebView.getEngine ();
         engine.executeScript (script);
      } else {
         this.m_Scripts.add (script);
      }
   }
}
